<template>
  <div id="userLoginPage">
    <h2 style="margin-bottom: 16px">用户登录</h2>
    <el-form
      :model="form"
      :style="{ width: '480px', margin: '0 auto' }"
      label-align="left"
      auto-label-width
    >
      <el-form-item field="userAccount" label="账号">
        <el-input v-model="form.userAccount" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item field="userPassword" label="密码">
        <el-input
          type="password"
          tooltip="密码长度不小于8位"
          v-model="form.userPassword"
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item>
        <div
          style="
            display: flex;
            justify-content: space-between;
            width: 100%;
            align-items: center;
          "
        >
          <el-button
            type="primary"
            html-type="submit"
            style="width: 120px"
            @click="handleSubmit"
            >Submit
          </el-button>
          <el-link href="/user/register">新用户注册</el-link>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from "vue";
import API from "@/api";
import { userLoginUsingPost } from "@/api/userController";
import { useLoginUserStore } from "@/store/userStore";

import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const loginUserStore = useLoginUserStore();
const router = useRouter();

const form = reactive({
  userAccount: "",
  userPassword: "",
} as API.UserLoginRequest);

const handleSubmit = async () => {
  console.log(form);
  const res = await userLoginUsingPost(form);
  if (res.data.code === 0) {
    await loginUserStore.fetchLoginUser();
    ElMessage({
      message: "登录完成",
      type: "success",
    });
    router.push({
      path: "/",
      replace: true,
    });
  } else {
    ElMessage({
      message: "登录失败," + res.data.message,
      type: "error",
    });
  }
};
</script>
